package com.mdwz.sunnyradio;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class History extends Activity {
	
	private MediaPlayer player;
	private JSONArray jsonArray;
	private List<Map<String, Object>> mData;
	private ListView lv;
	private MyAdapter adapter;
	private ProgressDialog mProgressDialog;
	
	public final class ViewHolder{
		public TextView title;
		public TextView info;
		public Button viewBtn;
		public String url;
        public String id;
	}
	
	public class MyAdapter extends BaseAdapter{

		private LayoutInflater mInflater;
		
		
		public MyAdapter(Context context){
			this.mInflater = LayoutInflater.from(context);
		}
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mData.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			
			ViewHolder holder = null;
			if (convertView == null) {
				
				holder=new ViewHolder();  
				
				convertView = mInflater.inflate(R.layout.list_history, null);
				holder.title = (TextView)convertView.findViewById(R.id.history_title);
				holder.info = (TextView)convertView.findViewById(R.id.history_info);
				holder.viewBtn = (Button)convertView.findViewById(R.id.view_btn);
				holder.viewBtn.setTag(holder);
				convertView.setTag(holder);
				
			}else {
				
				holder = (ViewHolder)convertView.getTag();
			}
			
			
			
			holder.title.setText((String)mData.get(position).get("history_title"));
			holder.info.setText((String)mData.get(position).get("history_info"));
			holder.url = (String)mData.get(position).get("url");
            holder.id = (String)mData.get(position).get("id");

			
			holder.viewBtn.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					
					ViewHolder holder = (ViewHolder)v.getTag();
					
					String title = holder.viewBtn.getText().toString();
					if ( title == "play" )
					{

                        player = new MediaPlayer();
                        player.setAudioStreamType(AudioManager.STREAM_MUSIC);

                        try {
                            player.setDataSource("http://sunny.ukulele.com.tw/stm/music/" + holder.id + "/radio.mp3");
                            player.prepare();
                        }
                        catch (IllegalArgumentException e) {
                            e.printStackTrace();
                        }
                        catch (IllegalStateException e) {
                            e.printStackTrace();
                        }
                        catch (IOException e) {
                            e.printStackTrace();
                        }
                        player.start();

						holder.viewBtn.setText( "stop");
					}
					else
					{
						player.stop();
						holder.viewBtn.setText( "play");
					}
									
				}
			});
			
			
			return convertView;
		}
		
	}
    
    private class HistoryTask extends AsyncTask<String, Void, String> {
    	
    	@Override
        protected void onPreExecute() {
            super.onPreExecute();
            mProgressDialog.show();
        }
    	
    	
        @Override
        protected String doInBackground(String... urls) {
 
            String result = "";
            try {
                
            	HttpClient httpclient = new DefaultHttpClient();
                HttpResponse httpResponse = httpclient.execute( new HttpGet( urls[0]) );
                result = EntityUtils.toString( httpResponse.getEntity() );
     
            } catch (Exception e) {
                
            }
     
            return result;
        }
        // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(String result) {
        	
        	try {
 		       jsonArray = new JSONArray( result );

 		    } catch (Exception e) {
 		      e.printStackTrace();
 		    }
        	
        	
        	mData = getData();
    		
    		lv.setAdapter(adapter);
    		
    		mProgressDialog.dismiss();
            
       }
    }

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_history);
		
		mProgressDialog = new ProgressDialog(History.this);
		mProgressDialog.setMessage("Loading...");
		mProgressDialog.setIndeterminate(true);
		mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		mProgressDialog.setCancelable(false);
		
		lv = (ListView)this.findViewById(R.id.history_listview1);
		adapter = new MyAdapter(this);
		
		HistoryTask htask = new HistoryTask();
		htask.execute("http://sunny.ukulele.com.tw/sunny/SunnyRadio/index.php/rest/programs");

	}
	
	private List<Map<String, Object>> getData() {
		
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		
		for (int i = 0; i < jsonArray.length(); i++) {
			
			JSONObject jsonObject = null;
			String name = null;
			String des = null;
			String url = null;
            String id = null;
			try{
				
				jsonObject  = jsonArray.getJSONObject(i);
                id = jsonObject.getString("id");
				name = jsonObject.getString("name");
				des = jsonObject.getString("description");
				url = jsonObject.getString("mp3_file_name");
				
			} catch (Exception e) {
			      e.printStackTrace();
			}
			
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("history_title",  name );
			map.put("history_info" ,  des );
			map.put("url" ,  url );
            map.put("id", id);
			list.add(map);
			
		}
		return list;
	}
/*	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		
		switch ( v.getId() ){
		case R.id.play_h:{
			player = new MediaPlayer();
	        player.setAudioStreamType(AudioManager.STREAM_MUSIC);

	        try {
	            player.setDataSource("http://www.hubharp.com/web_sound/BachGavotte.mp3");
	            player.prepare();
	        }
	        catch (IllegalArgumentException e) {
	            e.printStackTrace();
	        }
	        catch (IllegalStateException e) {
	            e.printStackTrace();
	        }
	        catch (IOException e) {
	            e.printStackTrace();
	        }
	        player.start();
	        btplay.setEnabled(false);
	         btstop.setEnabled(true);
			break;
		}
			
		case R.id.stop_h:{
			player.stop();
			 btplay.setEnabled(true);
	         btstop.setEnabled(false);
            break;
		}
		}
		
	}
*/
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.history, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		//player.stop();
	}
}
